<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自动注射器控制</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }

        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 30px 40px;
            max-height: 90vh;
            /* 新增：最大高度为视口高度的90% */
            overflow-y: auto;
            /* 新增：超出时出现垂直滚动条 */
        }

        .row {
            display: flex;
            flex-direction: row;
            align-items: center;
            margin-bottom: 10px;
        }

        .col {
            display: flex;
            flex-direction: column;
            margin: 0 10px;
        }

        .input-box {
            border: 2px solid #222;
            border-radius: 6px;
            padding: 8px 10px;
            font-size: 18px;
            margin-bottom: 10px;
            width: 120px;
            background: #fff;
        }

        .label {
            font-size: 18px;
            margin-bottom: 4px;
            text-align: center;
        }

        .big-btn {
            padding: 10px 20px;
            font-size: 18px;
            color: #fff;
            background-color: #007bff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 180px;
            text-align: center;
            margin: 10px 0;
        }

        .big-btn:active {
            background-color: #0056b3;
        }

        .input-row {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .input-label {
            font-size: 18px;
            width: 60px;
            text-align: right;
            margin-right: 8px;
        }

        .input-unit {
            font-size: 16px;
            margin-left: 6px;
        }
    </style>
    <script>

        // 校验是否为阿拉伯数字（整数或小数）
        function isNumber(val) {
            return /^(\d+)(\.\d+)?$/.test(val.trim());
        }

        // 复选框点击校验
        function checkBeforeCheck(rowIdx, checkbox) {
            var nameInput = document.querySelector(`#name${rowIdx}`);
            var totalInput = document.querySelector(`#total${rowIdx}`);
            if (!(nameInput.value.trim() && totalInput.value.trim())) {
                alert('请先输入药物名称和总量');
                checkbox.checked = false;
                return false;
            }
            return true;
        }

        // 修改后的 checkRowInputs，增加数字校验
        function checkRowInputs(rowIdx) {
            var nameInput = document.querySelector(`#name${rowIdx}`);
            var totalInput = document.querySelector(`#total${rowIdx}`);
            var checkbox = document.querySelector(`#check${rowIdx}`);
            // 校验总量是否为数字
            if (totalInput.value && !isNumber(totalInput.value)) {
                alert('总量请输入阿拉伯数字');
                totalInput.value = '';
            }
            // 不再控制disabled，只控制checked
            if (!(nameInput.value.trim() && totalInput.value.trim())) {
                checkbox.checked = false;
            }
        }

        // 速度和注射量校验
        function checkNumberInput(input, msg) {
            if (input.value && !isNumber(input.value)) {
                alert(msg);
                input.value = '';
            }
        }

        // 新增：初始化位置按钮逻辑，校验是否有未填写的药物和总量
        function initPosition() {
            // 校验与收集数据
            var drugs = [];
            var valid = false;
            for (var i = 1; i <= 3; i++) {
                var checkbox = document.querySelector(`#check${i}`);
                var nameInput = document.querySelector(`#name${i}`);
                var totalInput = document.querySelector(`#total${i}`);
                if (checkbox && checkbox.checked) {
                    if (!(nameInput.value.trim() && totalInput.value.trim())) {
                        alert('请先输入药物名称和总量');
                        return;
                    }
                    drugs.push({
                        name: nameInput.value.trim(),
                        total: parseFloat(totalInput.value),
                        checked: true
                    });
                    valid = true;
                } else {
                    drugs.push({
                        name: nameInput.value.trim(),
                        total: parseFloat(totalInput.value) || 0,
                        checked: false
                    });
                }
            }
            if (!valid) {
                alert('请先选择至少一种药物');
                return;
            }

            var options = [];
            for (var i = 1; i <= 3; i++) {
                var checkbox = document.querySelector(`#check${i}`);
                var nameInput = document.querySelector(`#name${i}`);
                if (checkbox.checked) {
                    options.push(nameInput.value.trim());
                }
            }
            var select = document.getElementById('drugSelect');
            select.innerHTML = '';
            options.forEach(function (opt) {
                var option = document.createElement('option');
                option.value = opt;
                option.text = opt;
                select.appendChild(option);
            });
            if (options.length > 0) {
                select.style.display = '';
            } else {
                select.style.display = 'none';
            }

            // 发送请求
            fetch('/initPosition', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ drugs: drugs })
            })
                .then(response => response.text())
                .then(data => alert(data))
                .catch(error => console.error('Error:', error));
        }

        async function startInjection() {
            var drugSelect = document.getElementById('drugSelect');
            var speedInput = document.querySelector('.input-row input[oninput*="速度"]');
            var amountInput = document.querySelector('.input-row input[oninput*="注射量"]');

            if (!drugSelect || drugSelect.style.display === 'none' || !drugSelect.value) {
                alert('请选择药物');
                return;
            }
            if (!speedInput.value.trim()) {
                alert('请输入速度');
                return;
            }
            if (!amountInput.value.trim()) {
                alert('请输入注射量');
                return;
            }

            try {
                // 1. 设置药物
                let res1 = await fetch('/setDrug?name=' + encodeURIComponent(drugSelect.value), { method: 'POST' });
                let text1 = await res1.text();
                if (!res1.ok) throw new Error(text1);

                // 2. 设置速度
                let res2 = await fetch('/setSpeed?value=' + encodeURIComponent(speedInput.value), { method: 'POST' });
                let text2 = await res2.text();
                if (!res2.ok) throw new Error(text2);

                // 3. 设置注射量
                let res3 = await fetch('/setAmount?value=' + encodeURIComponent(amountInput.value), { method: 'POST' });
                let text3 = await res3.text();
                if (!res3.ok) throw new Error(text3);

                // 4. 开始注射
                let res4 = await fetch('/start', { method: 'POST' });
                let text4 = await res4.text();
                alert(text4);
            } catch (err) {
                alert('操作失败: ' + err.message);
            }
        }

        function pauseInjection() {
            fetch('/pause', { method: 'POST' })
                .then(response => response.text())
                .then(data => alert(data))
                .catch(error => console.error('Error:', error));
            // alert('已暂停注射');
        }

        function resumeInjection() {
            fetch('/resume', { method: 'POST' })
                .then(response => response.text())
                .then(data => alert(data))
                .catch(error => console.error('Error:', error));
            // alert('已继续注射');
        }

        setInterval(function () {
            fetch('/injectStatus')
                .then(res => res.json())
                .then(data => {
                    if (data.finished) {
                        alert('注射已完成');
                    }
                });
        }, 1000);

        function updateRemain() {
            fetch('/drugStatus')
                .then(res => res.json())
                .then(data => {
                    if (data.remain) {
                        for (let i = 0; i < 3; i++) {
                            document.getElementById('remain' + (i + 1)).innerText = data.remain[i].toFixed(2);
                        }
                    }
                });
        }
        setInterval(updateRemain, 1000); // 每秒刷新一次
        window.onload = updateRemain;

        let holdInjecting = false;

        async function startHoldInjection(e) {
            e.preventDefault && e.preventDefault();
            if (holdInjecting) return;
            // 检查药物和速度
            var drugSelect = document.getElementById('drugSelect');
            var speedInput = document.querySelector('.input-row input[oninput*="速度"]');
            if (!drugSelect || drugSelect.style.display === 'none' || !drugSelect.value) {
                alert('请选择药物');
                return;
            }
            if (!speedInput.value.trim()) {
                alert('请输入速度');
                return;
            }
            holdInjecting = true;
            try {
                let url = `/holdStart?drug=${encodeURIComponent(drugSelect.value)}&speed=${encodeURIComponent(speedInput.value)}`;
                let res = await fetch(url, { method: 'POST' });
                let text = await res.text();
                if (!res.ok) throw new Error(text);
                // 可选：alert(text);
            } catch (err) {
                alert('操作失败: ' + err.message);
                holdInjecting = false;
            }
        }

        function stopHoldInjection(e) {
            if (!holdInjecting) return;
            holdInjecting = false;
            fetch('/holdStop', { method: 'POST' });
        }
    </script>
</head>

<body>
    <div class="container">
        <!-- 表头 -->
        <div class="row" style="justify-content: center;margin-right:70pt">
            <div style="width:30px; margin-right:8px;"></div>
            <div class="label" style="width:120px; text-align: center; margin-right:8px;">药物名称</div>
            <div class="label" style="width:70px; text-align: center; margin-right:8px;">总量</div>
            <div class="label" style="width:70px; text-align: center;">剩余</div>
        </div>
        <!-- 三行药物 -->
        <div class="row" style="justify-content: center;">
            <div style="width:30px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="check1" type="checkbox" style="width:30px;height:30px;"
                    onclick="return checkBeforeCheck(1, this)">
            </div>
            <div style="width:120px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="name1" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(1)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="total1" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(1)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center;">
                <span id="remain1" class="input-box"
                    style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;"
                    span>
                    <!-- <span id="remain1" class="input-box" style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;">mL</span> -->
            </div>
            <div class="label" style="width:70px; text-align: center;">mL</div>
        </div>
        <div class="row" style="justify-content: center;">
            <div style="width:30px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="check2" type="checkbox" style="width:30px;height:30px;"
                    onclick="return checkBeforeCheck(2, this)">
            </div>
            <div style="width:120px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="name2" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(2)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="total2" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(2)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center;">
                <span id="remain2" class="input-box"
                    style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;"
                    span>
                    <!-- <span id="remain2" class="input-box" style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;">mL</span> -->
            </div>
            <div class="label" style="width:70px; text-align: center;">mL</div>

        </div>
        <div class="row" style="justify-content: center;">
            <div style="width:30px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="check3" type="checkbox" style="width:30px;height:30px;"
                    onclick="return checkBeforeCheck(3, this)">
            </div>
            <div style="width:120px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="name3" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(3)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center; margin-right:8px;">
                <input id="total3" class="input-box" type="text" style="width:100%;" oninput="checkRowInputs(3)">
            </div>
            <div style="width:70px; display: flex; justify-content: center; align-items: center;">
                <span id="remain3" class="input-box"
                    style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;"
                    span>
                    
                    <!-- <span id="remain3" class="input-box" style="width:100%;display:flex;align-items:center;justify-content:center;box-sizing:border-box;">mL</span> -->
            </div>
            <div class="label" style="width:70px; text-align: center;">mL</div>

        </div>
        <!-- 初始化位置按钮 -->
        <button class="big-btn" style="margin-top: 16px; margin-bottom: 16px;" onclick="initPosition()">初始化</button>
        <!-- 药物、速度、注射量输入 -->
        <div
            style="display: flex; flex-direction: column; align-items: flex-start; width: 230px; margin: 0 auto 10px auto;">
            <div class="input-row" style="justify-content: flex-start; margin-bottom: 10px;">
                <span class="input-label" style="width: 70px; text-align: left;">药物:</span>
                <!-- 下拉框，初始隐藏 -->
                <select id="drugSelect" class="input-box" style="width: 140px; display: none;"></select>
            </div>
            <div class="input-row" style="justify-content: flex-start; margin-bottom: 10px;">
                <span class="input-label" style="width: 70px; text-align: left;">速度:</span>
                <input class="input-box" type="text" style="width: 140px;"
                    oninput="checkNumberInput(this, '速度请输入阿拉伯数字')">
                <span class="input-unit">mL/s</span>
            </div>
            <div class="input-row" style="justify-content: flex-start;">
                <span class="input-label" style="width: 70px; text-align: left;">注射量:</span>
                <input class="input-box" type="text" style="width: 140px;"
                    oninput="checkNumberInput(this, '注射量请输入阿拉伯数字')">
                <span class="input-unit">mL</span>
            </div>
        </div>
        <!-- 长按注射按钮 -->
        <button class="big-btn" onmousedown="startHoldInjection(event)" onmouseup="stopHoldInjection(event)"
            onmouseleave="stopHoldInjection(event)" ontouchstart="startHoldInjection(event)"
            ontouchend="stopHoldInjection(event)">
            长按注射
        </button>
        <!-- 操作按钮 -->
        <button class="big-btn" onclick="startInjection()">开始注射</button>
        <button class="big-btn" onclick="pauseInjection()">暂停注射</button>
        <button class="big-btn" onclick="resumeInjection()">继续注射</button>
        <button class="big-btn" onclick="window.location.href='/wifi'">WIFI</button>
        <button class="big-btn" onclick="window.location.href='/settings'">设置</button>

    </div>
</body>

</html>